#encoding=utf-8
'''
Created on 2014-12-9

@author: cooler
'''
import sys, logging, os, os.path
sys.path.append(os.getcwd()+"/utils" )
import logging.handlers
import traceback
import simplejson as json
from flask_script import Manager
from Config import initConfig
from flask import Flask, request,make_response, render_template, redirect,url_for, session, abort, current_app, g
from flask_principal import Principal, Permission, UserNeed, RoleNeed, Identity, AnonymousIdentity, identity_changed, identity_loaded
from service import create_app
from datetime import timedelta
app = create_app()
app.config['MAX_CONTENT_LENGTH'] = 1600 * 1024 * 1024

app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT'
app.permanent_session_lifetime = timedelta(seconds=20*60)

# 模板变量替换符合，冲突时使用，不建议这么做
# app.jinja_env.variable_start_string = '{{{{'
# app.jinja_env.variable_end_string = '}}}}'

logger = logging.getLogger()   
logfile = logging.handlers.TimedRotatingFileHandler(os.path.join(os.getcwd(), './logs/'+"suface"), 'D', 1, 0)
# 设置后缀名称，跟strftime的格式一样
logfile.suffix = "%Y%m%d%H.log"
logger.addHandler(logfile) 

formatter = logging.Formatter("%(asctime)s - %(name)s - %(filename)s - %(funcName)s - %(levelname)s - %(process)d - Line:%(lineno)d - %(message)s")  
logfile.setFormatter(formatter)   
logger.setLevel(logging.DEBUG) 

@app.before_request
def before_request():
    """Make sure we are connected to the database each request."""
    g.HEADERS =  request.headers
    g.args = request.args if request.method == 'GET' else request.form


manager = Manager(app)

principals = Principal(app)

@identity_loaded.connect_via(app)
def on_identity_loaded(sender, identity):
    identity.user = session.get("userinfo")
    if session.get("userinfo"):
        identity.provides.add(UserNeed(session.get("userinfo")['account']))
        for role in session.get("userinfo")['roles']:
            identity.provides.add(RoleNeed(role))


@app.route('/', methods=['GET'])
def index():
    return render_template('index.html')   


if __name__ == '__main__':
    # main()
    app.run(host='0.0.0.0',port=8088,debug=True)
